package org.changs.control.ui.carfile.video;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.changs.aplug.base.BaseFragment;
import org.changs.control.R;
import org.changs.control.databinding.LayoutRccViewBinding;
import org.changs.media.MediaFile;
import org.changs.media.MediaManager;
import org.changs.media.MediaSite;
import org.changs.media.MediaType;

import javax.inject.Inject;

/**
 * 全部视频
 * Created by Administrator on 2017/8/24.
 */

public class VideoFragment extends BaseFragment implements MediaManager.Callback {
    private LayoutRccViewBinding binding;

    @Inject
    MediaManager mMediaManager;

    private VideoAdapter mAdapter;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.layout_rcc_view, container, false);

        mMediaManager.registerCallback(this);
        initData(savedInstanceState);
        return binding.getRoot();
    }

    private void initData(Bundle savedInstanceState) {
        binding.rccView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new VideoAdapter(getContext(), mMediaManager.getMedia(MediaType.VIDEO, MediaSite.ALL), binding.rccView, mMediaManager);
        binding.rccView.setup()
                .adapter(mAdapter)
                .emptyText("没有视频~")
                .dynamic()
                .done();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMediaManager.unregisterCallback(this);
    }

    @Override
    public void delete(MediaFile mediaFile) {
        if (isNotEffective(mediaFile)) return;
        boolean remove = mAdapter.getData().remove(mediaFile);
        if (remove) mAdapter.notifyDataSetChanged();
    }

    @Override
    public void reload() {
        if (mAdapter == null) return;
        mAdapter.getData().clear();
        mAdapter.getData().addAll(mMediaManager.getMedia(MediaType.VIDEO, MediaSite.ALL));
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void upload(MediaFile mediaFile) {

    }

    private boolean isNotEffective(MediaFile mediaFile) {
        return mAdapter == null
                || mediaFile == null
                || mediaFile.getType() != MediaType.VIDEO;
    }
}
